﻿using UnityEngine;
using System.Collections;
using UnityExtensions;

/// <summary>
/// unity MonoBehaviour单例模板
/// </summary>
/// <typeparam name="T"></typeparam>
public class SingletonMonoAsync<T> : MonoBehaviour where T : SingletonMonoAsync<T>, new()
{
    protected static T s_Instance = null;
    /// <summary>
    /// 检测实例是否为null的标志
    /// 用于解决unity new Object() == null 为true的情况
    /// </summary>
    protected static bool instanceIsNull = true;
    static object locked = new object();
    /// <summary>
    /// 取得当前对象的一个单例
    /// </summary>
    public static T instance
    {
        get
        {
            lock (locked)
            {
                if (instanceIsNull)
                {
                    var ins = FindObjectOfType<T>();
                    if (!ins)
                    {
                        var mainObj = GameObjectUtility.FindOrNew("Main");
                        ins = mainObj.AddComponent<T>();
                    }
                    ins.AppyInstance();
                }
            }
            return s_Instance;
        }
    }
    protected virtual void Awake()
    {
        AppyInstance();
    }
    protected virtual void Start()
    {

    }
    protected void AppyInstance()
    {
        if (instanceIsNull)
        {
            s_Instance = this as T;
            instanceIsNull = false;
        }
    }
}
/// <summary>
/// C#单例模板
/// </summary>
/// <typeparam name="T"></typeparam>
public class SingletonObjectAsync<T> where T : class, new()
{
    protected static T _this = null;
    static object locked = new object();
    /// <summary>
    /// 取得当前对象的一个单例
    /// </summary>
    public static T Instance
    {
        get
        {
            lock (locked)
            {
                if (_this == null)
                {
                    _this = new T();
                }
            }
            return _this;
        }
    }
}
